import React, {useState} from "react";
import {Button, Chip, Divider, Grid, Paper, Typography} from "@material-ui/core";
import MenuDropDown from "../../../../Common/MenuDropDown/MenuDropDown";
import {useDispatch} from "react-redux";
import {selectDeselectContextActivity} from "../../../../../../../redux/reducers/editor";
import DoneIcon from "@material-ui/icons/Done";

export default function ContextDetails(props) {
  // Props
  const {classes, contextActivitiesData, selectedContextActivities, styles} = props;

  // Local constants
  const dispatch = useDispatch();
  const [selection, setSelection] = useState({
    contextActivities: {id: "", name: "", values: []},
    details: {id: "", name: "", values: []},
    values: {id: "", name: ""},
    chips: selectedContextActivities ? selectedContextActivities : [],
  });

  const handleChooseContextActivities = (label, value) => {
    if (label === "contextActivities") {
      setSelection({
        ...selection,
        [label]: value,
        details: {id: "", name: "", values: []},
        values: {id: "", name: ""},
      });
    } else if (label === "details") {
      setSelection({
        ...selection,
        [label]: value,
        values: {id: "", name: ""},
      })
    } else {
      setSelection({
        ...selection,
        [label]: value
      });
    }
  };

  const handleAddContextActivity = () => {
    let newDetailsValue = [];
    let newValue = [];
    let newContextActivitiesData = contextActivitiesData;
    newContextActivitiesData.forEach(contextData => {
      if (contextData.id === selection.contextActivities.id) {
        contextData.values.forEach(detailsData => {
          if (detailsData.id === selection.details.id) {
            newDetailsValue = selection.details.values.filter(a => a.id !== selection.values.id);
            detailsData.values = newDetailsValue;
          } else if (detailsData.id === selection.values.id) {
            newValue = selection.contextActivities.values.filter(a => a.id !== selection.values.id);
            contextData.values = newValue;
          }
        })
      }
    })
    const newChips = selection.chips;
    newChips.push({
      pId: selection.contextActivities.id,
      pName: selection.contextActivities.name,
      id: selection.details.id,
      name: selection.details.name,
      values: selection.values
    });
    setSelection({
      ...selection,
      contextActivities: {
        ...selection.contextActivities,
        values: newValue.length !== 0 ? newValue : selection.contextActivities.values
      },
      details: {
        ...selection.details,
        values: newDetailsValue.length !== 0 ? newDetailsValue : selection.details.values
      },
      values: {id: "", name: ""}
    })
    dispatch(selectDeselectContextActivity(newChips, newContextActivitiesData));
  };

  const handleDeleteContextActivity = (chip) => {
    let newContextActivitiesData = contextActivitiesData;
    newContextActivitiesData.forEach(contextData => {
      if (contextData.id === chip.pId) {
        contextData.values.forEach(detailsData => {
          if (detailsData.id === chip.id) {
            detailsData.values.push({id: chip.values.id, name: chip.values.name});
            detailsData.values = detailsData.values.sort((a, b) => (a.name > b.name) ? 1 : -1);
          }
        })
        if (!chip.name) {
          contextData.values.push({id: chip.values.id, name: chip.values.name});
          contextData.values = contextData.values.sort((a, b) => (a.name > b.name) ? 1 : -1);
        }
      }
    })
    const newChips = selection.chips.filter(a => a.values.id !== chip.values.id);
    setSelection({
      ...selection,
      details: {id: "", name: "", values: []},
      values: {id: "", name: ""},
      chips: newChips
    })
    dispatch(selectDeselectContextActivity(newChips, newContextActivitiesData))
  }

  const handleClearAllContextActivities = () => {
    let newContextActivitiesData = contextActivitiesData;
    let newChips = []
    selection.chips.forEach(chip => {
      newContextActivitiesData.forEach(contextData => {
        if (contextData.id === chip.pId) {
          contextData.values.forEach(detailsData => {
            if (detailsData.id === chip.id) {
              detailsData.values.push({id: chip.values.id, name: chip.values.name});
              detailsData.values = detailsData.values.sort((a, b) => (a.name > b.name) ? 1 : -1);
            }
          })
          if (!chip.name) {
            contextData.values.push({id: chip.values.id, name: chip.values.name});
            contextData.values = contextData.values.sort((a, b) => (a.name > b.name) ? 1 : -1);
          }
        }
      })
    })
    setSelection({
      ...selection,
      details: {id: "", name: "", values: []},
      values: {id: "", name: ""},
      chips: newChips
    })
    dispatch(selectDeselectContextActivity(newChips, newContextActivitiesData))
  }

  return (
    <>
      <Grid container direction="column">
        <Grid item className={classes.gutterTopBottom}>
          <Paper elevation={10}>
            <Grid container direction="row">
              <Grid item xs>
                <MenuDropDown
                  displayLabel={"Related activities"}
                  parameterName={"contextActivities"}
                  source={contextActivitiesData}
                  value={selection.contextActivities.name}
                  handleSelection={handleChooseContextActivities}
                />
              </Grid>

              {selection.contextActivities.name === "Parent" ||
              selection.contextActivities.name === "Grouping" ||
              selection.contextActivities.name === "Category" ||
              selection.contextActivities.name === "Other" ? (
                <>
                  <Grid item xs>
                    <MenuDropDown
                      middle={true}
                      displayLabel={"Details"}
                      parameterName={"details"}
                      source={selection.contextActivities.values}
                      value={selection.details.name}
                      handleSelection={handleChooseContextActivities}
                    />
                  </Grid>
                  <Grid item xs>
                    <MenuDropDown
                      middle={true}
                      displayLabel={"Values"}
                      parameterName={"values"}
                      source={selection.details.values}
                      value={selection.values.name}
                      handleSelection={handleChooseContextActivities}
                    />
                  </Grid>
                </>
              ) : selection.contextActivities.name === "Instructor" ||
              selection.contextActivities.name === "Platform" ? (
                  <Grid item xs>
                    <MenuDropDown
                      middle={true}
                      displayLabel={"Values"}
                      parameterName={"values"}
                      source={selection.contextActivities.values}
                      value={selection.values.name}
                      handleSelection={handleChooseContextActivities}
                    />
                  </Grid>
                ) :
                //   selection.contextActivities.name === "Extensions" ? (
                //   <>
                //     <MenuDropDown
                //       middle={true}
                //       label={"Extension types"}
                //       source={contextExtensions}
                //       value={selection.extension.name}
                //       handleSelection={handleChooseContextActivities}
                //     />
                //     <MenuDropDown
                //       middle={true}
                //       label={"Value"}
                //       source={valueData}
                //       value={selection.value.name}
                //       handleSelection={handleChooseContextActivities}
                //     />
                //   </>
                // ) :
                (
                  <></>
                )}
              <Button
                disabled={selection.values.name === ""}
                onClick={handleAddContextActivity}
                variant="contained"
                color="primary"
                className={styles.applyButton}
              >
                Select
              </Button>
            </Grid>
          </Paper>
        </Grid>
        <Grid container justify="space-between" alignItems="center" className={classes.gutterTopBottom}>
          <Grid item>
            <Typography variant="overline">Selected Related activities</Typography>
          </Grid>
          <Grid item>
            <Button
              color="primary" size="small" variant="outlined"
              onClick={handleClearAllContextActivities}
              // selectActivityTypes.length !== 0 ? () => setClearError(!clearError) :
              disabled={selection.chips.length === 0}
            >
              <Typography variant="overline">Clear selections</Typography>
            </Button>
          </Grid>
        </Grid>
        <Grid item style={{minHeight: 40}}>
          {selection.chips.map((chip, index) => {
            return (
              <Chip
                key={index}
                label={chip.name ?
                  chip.pName + " | " + chip.name + " | " + chip.values.name :
                  chip.pName + " | " + chip.values.name
                }
                variant="default"
                onDelete={() => handleDeleteContextActivity(chip)}
                // selectActivityTypes.length !== 0 ? () => setClearError(!clearError) :
                color="primary"
                className={styles.chipMargin}
              />
            )
          })}
        </Grid>
        <Grid item className={classes.gutterBottom}>
          <Divider/>
        </Grid>
      </Grid>
    </>
  );
}
